<template>
  <div class="app-container">
    <el-button :loading="downloadLoading" style="margin:0 0 20px 20px;" type="primary" icon="el-icon-document" @click="handleDownload">
        模板下载
      </el-button>
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { addRole } from '../../api/uploadExcel'
import { Loading } from 'element-ui'
import { fetchExcelTemplate, fetchExcelData } from '../../api/downloadExcel'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: [],
      downloadLoading: false
    }
  },
  created() {
    console.log(this.$route.path, '---')
  },
  methods: {
    async beforeUpload(file) {
      const loadingView = Loading.service({ fullscreen: true })
      var formData = new FormData()
      formData.append('multipartFile', file)
      if (this.$route.path === '/bring-into/upload-know-the-facts-excel') {
        formData.append('type', '1')
      }
      if (this.$route.path === '/bring-into/upload-bring-into-questionnaire') {
        formData.append('type', '2')
      }
      if (this.$route.path === '/test-meal/upload-test-meal-questionnaire') {
        formData.append('type', '3')
      }
      try {
        const res = await addRole(formData)

        loadingView.close()
      } catch {
        loadingView.close()
      }

      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      localStorage.setItem(this.$route.path, JSON.stringify(results))
      // console.log(results, header, 'results')
      this.tableData = results
      this.tableHeader = header
    },
    handleDownload() {
      window.open('http://101.34.88.117:8082/excel/generateTemplate')
    }
  }
}
</script>
